package packet

import (
	"Bulb/data"
	"encoding/json"
	"log"
)

type ServerPacket struct {
	Type string      `json:"type"`
	Data interface{} `json:"data"`
}

type ClientPacket struct {
	Action string `json:"action"`
	Data   string `json:"data"`
}

func NewOnlineCountPacket(count int) *ServerPacket {
	return &ServerPacket{Type: "online_count", Data: count}
}

func NewChatMessagePacket(message data.Message) *ServerPacket {
	return &ServerPacket{Type: "chat_message", Data: message}
}
func NewChatMessageInitPacket(messages []data.Message) *ServerPacket {
	return &ServerPacket{Type: "chat_message_init", Data: messages}
}
func NewBulbSetPacket(status string) *ServerPacket {
	return &ServerPacket{Type: "bulb-set", Data: status}
}
func NewUpdateLightBulbPacket(userData data.UserData) *ServerPacket {
	return &ServerPacket{Type: "update_lightbulb", Data: userData}
}
func NewUserDataInitPacket(userDatas []data.UserData) *ServerPacket {
	return &ServerPacket{Type: "user_data_init", Data: userDatas}
}

func ParseClientPacket(strPacket string) (pack ClientPacket) {
	err := json.Unmarshal([]byte(strPacket), &pack)
	if err != nil {
		log.Println(err)
	}
	return
}

func EncodeServerPacket(pack *ServerPacket) []byte {
	str, err := json.Marshal(pack)
	if err != nil {
		log.Println(err)
		return nil
	}
	return str
}
